package com.sls.nzdapplication.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;


import com.sls.nzdapplication.R;
import com.sls.nzdapplication.app.MySharedPreferences;
import com.sls.nzdapplication.ui.activity.user.LoggedInUserView;
import com.sls.nzdapplication.ui.activity.user.LoginFormState;
import com.sls.nzdapplication.ui.activity.user.LoginResult;
import com.sls.nzdapplication.ui.activity.user.LoginViewModel;
import com.sls.nzdapplication.ui.activity.user.LoginViewModelFactory;
import com.sls.nzdapplication.util.DeviceUtils;

import es.dmoral.toasty.Toasty;
import me.jessyan.autosize.internal.CustomAdapt;


public class LoginActivity extends AppCompatActivity implements CustomAdapt {

    private LoginViewModel loginViewModel;

    private MySharedPreferences mySharedPreferences;

    private EditText usernameEditText;

    private EditText passwordEditText;

    private EditText serverEditText;

    private EditText macCodeView;

    private ProgressBar loadingProgressBar;

    private EditText loginCodeEditView;

    private Switch loginTypeView;

    private boolean islocalLogin = true;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        loginViewModel = new ViewModelProvider(this, new LoginViewModelFactory())
                .get(LoginViewModel.class);

        usernameEditText = findViewById(R.id.username);

        passwordEditText = findViewById(R.id.password);
        serverEditText = findViewById(R.id.server_address);
        macCodeView = findViewById(R.id.mac_code);
        System.err.println(DeviceUtils.getUUid());
        macCodeView.setText(DeviceUtils.getUUid());
        serverEditText.setVisibility(View.GONE);
        serverEditText.setText("http://122.96.144.125:9527");
        final Button loginButton = findViewById(R.id.login);
        loadingProgressBar = findViewById(R.id.loading);
        loginTypeView = findViewById(R.id.login_type);
        loginCodeEditView= findViewById(R.id.local_code);
        loginCodeEditView.setHintTextColor(getResources().getColor(R.color.gsp_loc_selected));
        if(islocalLogin){
            loginButton.setEnabled(true);
        }
        loginTypeView.setVisibility(View.INVISIBLE);

        loginTypeView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                islocalLogin = b;
                if(b){
                    loginButton.setEnabled(true);
                    usernameEditText.setVisibility(View.INVISIBLE);
                    passwordEditText.setVisibility(View.INVISIBLE);
                    serverEditText.setVisibility(View.INVISIBLE);
                    macCodeView.setVisibility(View.VISIBLE);
                    loginCodeEditView.setVisibility(View.VISIBLE);
                }else{
                    loginButton.setEnabled(false);
                    usernameEditText.setVisibility(View.VISIBLE);
                    passwordEditText.setVisibility(View.VISIBLE);
//                    serverEditText.setVisibility(View.VISIBLE);
                    macCodeView.setVisibility(View.INVISIBLE);
                    loginCodeEditView.setVisibility(View.INVISIBLE);
                }

            }
        });

        mySharedPreferences = new MySharedPreferences(getApplicationContext());

        loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
            @Override
            public void onChanged(@Nullable LoginFormState loginFormState) {
                if (loginFormState == null) {
                    return;
                }
                    loginButton.setEnabled(loginFormState.isDataValid());

                if (loginFormState.getUsernameError() != null) {
                    usernameEditText.setError(getString(loginFormState.getUsernameError()));
                }
                if (loginFormState.getPasswordError() != null) {
                    passwordEditText.setError(getString(loginFormState.getPasswordError()));
                }
                if (loginFormState.getServerError() != null) {
                    passwordEditText.setError(getString(loginFormState.getServerError()));
                }
            }
        });

        loginViewModel.getLoginResult().observe(this, new Observer<LoginResult>() {
            @Override
            public void onChanged(@Nullable LoginResult loginResult) {
                if (loginResult == null) {
                    return;
                }
                loadingProgressBar.setVisibility(View.GONE);
                if (loginResult.getError() != null) {
                    showLoginFailed(loginResult.getError());
                }
                if (loginResult.getSuccess() != null) {
                    updateUiWithUser(loginResult.getSuccess());
                }
                setResult(Activity.RESULT_OK);

                //Complete and destroy login activity once successful
                finish();
            }
        });

        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
                loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString(),serverEditText.getText().toString());
            }
        };
        usernameEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.addTextChangedListener(afterTextChangedListener);
        serverEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    LoginTask loginTask = new LoginTask(getApplicationContext());
                    loginTask.execute(usernameEditText.getText().toString(),
                            passwordEditText.getText().toString(),serverEditText.getText().toString());
                }
                return false;
            }
        });

        loginCodeEditView.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                   localLogin(loginCodeEditView.getText().toString());
                }
                return false;
            }
        });

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!islocalLogin){
                    LoginTask loginTask = new LoginTask(getApplicationContext());
                    loginTask.execute(usernameEditText.getText().toString(),
                            passwordEditText.getText().toString(),serverEditText.getText().toString());
                }else {
                    localLogin(loginCodeEditView.getText().toString());
                }

            }
        });

        initLogin();
    }

    private void initLogin(){
//        deleteDatabase("xj.db");

        if(!"".equals(mySharedPreferences.getUserValue("token"))){
            int codeinfo = DeviceUtils.isAuthorized(mySharedPreferences.getUserValue("token"),getApplicationContext());
            if(codeinfo==2){
                Toasty.error(LoginActivity.this, "注册码已过期,请重新注册", Toast.LENGTH_LONG, true).show();
                return;
            }else{
                startActivity(new Intent(LoginActivity.this, MyActivity.class));
                this.finish();
            }

        }
    }

    private void localLogin(String code){
        if(code.equals("")){
            Toasty.error(LoginActivity.this, "注册码不允许为空", Toast.LENGTH_LONG, true).show();
            return;
        }
        int codeinfo = DeviceUtils.isAuthorized(code,getApplicationContext());
        if(codeinfo==-1){
            Toasty.error(LoginActivity.this, "注册码不正确", Toast.LENGTH_LONG, true).show();
            return;
        }
        else if(codeinfo==1){
            Toasty.error(LoginActivity.this, "注册码不匹配", Toast.LENGTH_LONG, true).show();
            return;
        }
        else if(codeinfo==2){
            Toasty.error(LoginActivity.this, "注册码已过期", Toast.LENGTH_LONG, true).show();
            return;
        }

        mySharedPreferences.clearUserInfo();
        mySharedPreferences.saveUserInfo("本地操作员",code,"local");
        startActivity(new Intent(LoginActivity.this, MyActivity.class));
//        startActivity(new Intent(com.sls.autoc.application.ui.activity.LoginActivity.this, MapActivity.class));
        this.finish();
    }

    private void updateUiWithUser(LoggedInUserView model) {
        String welcome = getString(R.string.welcome) + model.getDisplayName();
        // TODO : initiate successful logged in experience
        Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
    }

    private void showLoginFailed(@StringRes Integer errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean isBaseOnWidth() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            return true;//根据宽度适配
        } else {
            return false;//根据高度适配
        }
    }

    @Override
    public float getSizeInDp() {
        // 横屏下的高度不就是竖屏的宽度吗,所以统一返回宽度即可
        return 500;
    }

    class LoginTask extends AsyncTask<String, Integer, com.alibaba.fastjson.JSONObject> {
        private Context mContext;
        private String server;


        public LoginTask(Context context){
            this.mContext = context;
        }

        @Override
        protected void onPreExecute() {
            loadingProgressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected com.alibaba.fastjson.JSONObject doInBackground(String... strings) {
            server = strings[2];
            return loginViewModel.login(strings[0], strings[1],strings[2]);
        }

        @Override
        protected void onPostExecute(com.alibaba.fastjson.JSONObject jsonObject) {
            super.onPostExecute(jsonObject);
            if(null !=jsonObject.getString("id")){
                mySharedPreferences.saveUserInfo(jsonObject.getString("username"),jsonObject.getString("token"),server);
                startActivity(new Intent(LoginActivity.this, MyActivity.class));
                LoginActivity.this.finish();
            }else{
                loadingProgressBar.setVisibility(View.GONE);

//                Toasty.error(mContext, "登录失败！", Toast.LENGTH_SHORT,true).show();
            }
        }
    }
}